package leetcode;

/**
 * @Author: Yangu
 * @Created time: 2021/1/28 22:46
 * @Description :
 */
public class 两数相加 {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode();
        int value = l1.val + l2.val;
        l3.val = value % 10;
        if(value/10 >0 || l1.next != null || l2.next != null) {
            l3.next = new ListNode(value/10, null);
        }
        ListNode node1 = l1.next;
        ListNode node2 = l2.next;
        ListNode node3 = l3.next;
        int needAddOne = 0;
        if(value/10 > 0) {
            needAddOne = 1;
        }
        while(node1 != null || node2 != null) {
            int node3Value = 0;
            if(node1 == null) {
                node3Value = node2.val  + needAddOne;
                node3.val = node3Value % 10;
                node1 = null;
                node2 = node2.next;

            } else if(node2 == null) {
                node3Value = node1.val  + needAddOne;
                node3.val = node3Value % 10;
                node2 = null;
                node1 = node1.next;
            } else {
                node3Value = node1.val + node2.val + needAddOne;
                node3.val = node3Value % 10;
                node2 = node2.next;
                node1 = node1.next;
            }
            if(node3Value/10 >0 || node1 != null || node2 !=null) {
                node3.next = new ListNode(node3Value/10, null);
            }
            if(node3Value/10 >0) {
                needAddOne = 1;
            } else {
                needAddOne = 0;
            }
            node3 = node3.next;
        }
        return l3;
    }


    public static void main(String[] args) {
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(5, null)));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4, null)));

        new 两数相加().addTwoNumbers(l1, l2);
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
